<template>

<el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="标题">
      <el-input v-model="formInline.title" placeholder="请输入标题或者关键字" clearable />
    </el-form-item>

    <el-form-item label="上传时间">
      <el-col :span="11">
        <el-form-item prop="date1">
          <el-date-picker
            v-model="formInline.startTime"
            type="date"
            aria-label="开始时间"
            placeholder="开始时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col class="text-center" :span="2">
        <span class="text-gray-500">-</span>
      </el-col>
      <el-col :span="11">
        <el-form-item prop="date2">
          <el-time-picker
            v-model="formInline.endTime"
            aria-label="Pick a time"
            placeholder="结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form-item>
  </el-form>

  <!-- 轮播图列表头部 -->
  <div class="carousel-header">
    <div class="header-left">
      <el-icon class="header-icon"><Grid /></el-icon>
      <span class="header-title">轮播图列表</span>
      <span v-if="selectedRows.length > 0" class="selection-info">
        已选择 {{ selectedRows.length }} 项
      </span>
    </div>
    <div class="header-right">
      <!-- 批量操作按钮 -->
      <div v-if="selectedRows.length > 0" class="batch-operations">
        <el-button @click="selectAll">全选</el-button>
        <el-button @click="clearSelection">取消全选</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </div>
      <el-button type="primary" @click="addCarousel">新增轮播图</el-button>
    </div>
  </div>

  <el-table :data="tableData" border style="width: 100%" ref="tableRef" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" type="index" label="序号"  />
    <el-table-column prop="title" label="轮播图标题"  />
    <el-table-column prop="imageUrl" label="轮播图" width="180">
         <template v-slot="scope">
            <div class="table-image-container" @click="previewImage(scope.row.imageUrl)">
                <img 
                    class="table-image" 
                    :src="scope.row.imageUrl"
                    :alt="scope.row.title"
                    @error="handleImageError"
                />
            </div>
        </template>
    </el-table-column>
    <el-table-column prop="status" label="状态"  >
        <template v-slot="a">
            <el-tag type="primary" v-if="a.row.status===true">上架</el-tag>
            <el-tag type="danger" v-if="a.row.status===false">下架</el-tag>
        </template>
    </el-table-column>
    <el-table-column prop="startTime" label="上传时间"  >
        <template v-slot="a">
                <span>
                {{ moment(a.row.createTime || a.row.createdAt || a.row.uploadTime || a.row.startTime).format("YYYY-MM-DD HH:mm:ss") }}
                </span>
        </template>
    </el-table-column>
    <el-table-column prop="endTime" label="失效时间"  >
         <template v-slot="a">
                <span>
                {{ moment(a.row.expireTime || a.row.expiredAt || a.row.validUntil || a.row.endTime).format("YYYY-MM-DD HH:mm:ss") }}
                </span>
        </template>
    </el-table-column>
    <el-table-column  label="操作" >
        <template v-slot="a">
            <el-button @click="editCarousel(a.row)">编辑</el-button>
            <el-button type="danger" @click="deleteCarousel(a.row)">删除</el-button>
        </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="formInline.pageIndex"
      v-model:page-size="formInline.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagin.totaleCount"
    />
  </div>

  <!-- 新增轮播图对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑轮播图' : '新增轮播图'"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="carouselFormRef"
      :model="carouselForm"
      :rules="carouselRules"
      label-width="120px"
      class="carousel-form"
    >
      <!-- 轮播图标题 -->
      <el-form-item label="轮播图标题" prop="title" required>
        <el-input
          v-model="carouselForm.title"
          placeholder="请输入..."
          clearable
        />
      </el-form-item>

      <!-- 轮播图上传 -->
      <el-form-item label="轮播图" prop="imageUrl" required>
                 <el-upload
             class="avatar-uploader"
             action="#"
             :show-file-list="false"
             :on-success="handleAvatarSuccess"
             :before-upload="beforeAvatarUpload"
             :http-request="customUpload"
             :auto-upload="true"
         >
             <img v-if="carouselForm.imageUrl" :src="carouselForm.imageUrl" class="avatar" />
             <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
         </el-upload>
      </el-form-item>

      <!-- 轮播图状态 -->
      <el-form-item label="轮播图状态" prop="status">
        <el-switch
          v-model="carouselForm.status"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

      <!-- 轮播图链接地址 -->
      <el-form-item label="轮播图链接地址" prop="linkUrl" >
        <el-input
          v-model="carouselForm.linkUrl"
          placeholder="请输入..."
          clearable
        />
      </el-form-item>

      <!-- 排序 -->
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="carouselForm.sortOrder"
          placeholder="请输入..."
          clearable
        />
        <span class="sort-tip">填写数字，数字越大越靠前</span>
      </el-form-item>

      <!-- 开始时间 -->
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="carouselForm.startTime"
          type="datetime"
          placeholder="选择开始时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 结束时间 -->
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="carouselForm.endTime"
          type="datetime"
          placeholder="选择结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="isEdit ? updateCarousel() : AddCarousel()">提交</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 图片预览对话框 -->
  <el-dialog 
    v-model="imagePreviewVisible" 
    title="图片预览" 
    width="60%" 
    :before-close="() => imagePreviewVisible = false"
    class="image-preview-dialog"
  >
    <div class="image-preview-container">
      <img 
        :src="previewImageUrl" 
        alt="预览图片" 
        class="preview-image"
        @error="handleImageError"
      />
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { showCarouselChart, addPCarouselChart, uploadImage, UpdatePCarouselChart, deleteCarouselChart } from '@/HTTPS/server';
import { reactive } from 'vue';
import moment from 'moment';
import { Grid, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import type { UploadProps } from 'element-plus'

onMounted(()=>{
    show();
})


const formInline = reactive({
  title: '',
  startTime:"",
  endTime: '',
  pageIndex: 1,
  pageSize:10
  
})

const onSubmit = () => {
  console.log('submit!')
  formInline.pageIndex = 1; // 重置到第一页
  show();
}

//重置
const onReset = () => {
  console.log('reset!')
  // 重置查询条件
  formInline.title = '';
  formInline.startTime = '';
  formInline.endTime = '';
  formInline.pageIndex = 1;
  formInline.pageSize = 10;
  // 刷新列表
  show();
}

// 分页数据
const pagin = ref({
    totaleCount: 0,
    pageCount: 0,
})

// 监听分页参数变化
watch(formInline, () => {
    show();
}, { deep: true })

//显示
const tableData = ref([])
const show=()=>{
    showCarouselChart(formInline).then(res=>{
        console.log('API返回的数据:', res.data.data.list);
        tableData.value = res.data.data.list;
        pagin.value.pageCount = res.data.data.pageCount;
        pagin.value.totaleCount = res.data.data.totaleCount;
        // 清空选中状态
        selectedRows.value = [];
    })
}

// 表格选择相关
const tableRef = ref();
const selectedRows = ref<any[]>([]);

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection;
    console.log('当前选中的行:', selection);
}

// 全选
const selectAll = () => {
    if (tableRef.value) {
        tableData.value.forEach(row => {
            tableRef.value.toggleRowSelection(row, true);
        });
    }
}

// 取消全选
const clearSelection = () => {
    if (tableRef.value) {
        tableRef.value.clearSelection();
    }
}

// 对话框控制
const dialogVisible = ref(false);
const carouselFormRef = ref();
const isEdit = ref(false);
const currentEditId = ref(null);

// 轮播图表单数据
const carouselForm = reactive({
    title: '',
    imageUrl: '',
    status: true,
    linkUrl: '',
    sortOrder: '',
    startTime: null as Date | null,
    endTime: null as Date | null
});

// 表单验证规则
const carouselRules = {
    title: [
        { required: true, message: '请输入轮播图标题', trigger: 'blur' }
    ],
    imageUrl: [
        { required: true, message: '请上传轮播图', trigger: 'change' }
    ],
    startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' }
    ]
};

// 新增轮播图
const addCarousel = () => {
    isEdit.value = false;
    currentEditId.value = null;
    dialogVisible.value = true;
    // 重置表单
    resetCarouselForm();
}

// 编辑轮播图
const editCarousel = (row: any) => {
    isEdit.value = true;
    currentEditId.value = row.id;
    console.log('编辑轮播图，ID:', row.id, '完整数据:', row);
    dialogVisible.value = true;
    
    // 填充表单数据
    carouselForm.title = row.title || '';
    carouselForm.imageUrl = row.imageUrl || '';
    carouselForm.status = row.status !== undefined ? row.status : true;
    carouselForm.linkUrl = row.linkUrl || '';
    carouselForm.sortOrder = row.sortOrder || row.sort || '';
    carouselForm.startTime = row.startTime || row.createTime || row.createdAt || null;
    carouselForm.endTime = row.endTime || row.expireTime || row.expiredAt || null;
    
    if (carouselFormRef.value) {
        carouselFormRef.value.clearValidate();
    }
}

// 重置表单
const resetCarouselForm = () => {
    carouselForm.title = '';
    carouselForm.imageUrl = '';
    carouselForm.status = true;
    carouselForm.linkUrl = '';
    carouselForm.sortOrder = '';
    
    // 设置默认时间：开始时间为当前时间，结束时间为一个月后
    const now = new Date();
    const oneMonthLater = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);
    
    carouselForm.startTime = now;
    carouselForm.endTime = oneMonthLater;
    
    if (carouselFormRef.value) {
        carouselFormRef.value.clearValidate();
    }
}

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false;
    isEdit.value = false;
    currentEditId.value = null;
    resetCarouselForm();
}

// 自定义上传方法
const customUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    
    console.log('开始上传文件到MinIO:', file);
    
    let fileToUpload = file;
    
    // 如果图片大于1MB，进行压缩
    if (fileToUpload.size / 1024 / 1024 > 1) {
        try {
            fileToUpload = await compressImage(fileToUpload);
            console.log(`图片已压缩：${(file.size / 1024 / 1024).toFixed(2)}MB -> ${(fileToUpload.size / 1024 / 1024).toFixed(2)}MB`);
            ElMessage.success(`图片已自动压缩：${(file.size / 1024 / 1024).toFixed(2)}MB -> ${(fileToUpload.size / 1024 / 1024).toFixed(2)}MB`);
        } catch (error) {
            console.error('图片压缩失败:', error);
            ElMessage.warning('图片压缩失败，将使用原图上传');
        }
    }
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', fileToUpload);
    
    // 调用上传API
    uploadImage(formData)
        .then(res => {
            console.log('上传响应:', res);
            
            if (res.data.code === 200 || res.status === 200) {
                // 从响应中获取图片URL
                let imageUrl = res.data.data?.url || res.data.data?.imageUrl || res.data.data || res.data.url;
                
                // 确保URL是完整的
                if (imageUrl && !imageUrl.startsWith('http')) {
                    imageUrl = 'http://8.141.112.218:9000' + (imageUrl.startsWith('/') ? imageUrl : '/' + imageUrl);
                }
                
                console.log('处理后的图片URL:', imageUrl);
                carouselForm.imageUrl = imageUrl;
                
                ElMessage.success('图片上传成功');
                onSuccess(res.data);
            } else {
                ElMessage.error('图片上传失败');
                onError(new Error('上传失败'));
            }
        })
        .catch(error => {
            console.error('上传错误:', error);
            ElMessage.error('图片上传失败');
            onError(error);
        });
}

const handleAvatarSuccess=(imgs:any) => {
    console.log('上传成功回调:', imgs);
    carouselForm.imageUrl = imgs
    carouselForm.linkUrl = imgs
}

// 图片压缩函数
const compressImage = (file: File, maxWidth: number = 800, maxHeight: number = 600, quality: number = 0.8): Promise<File> => {
    return new Promise((resolve) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d')!;
        const img = new Image();
        
        img.onload = () => {
            // 计算压缩后的尺寸
            let { width, height } = img;
            
            if (width > height) {
                if (width > maxWidth) {
                    height = (height * maxWidth) / width;
                    width = maxWidth;
                }
            } else {
                if (height > maxHeight) {
                    width = (width * maxHeight) / height;
                    height = maxHeight;
                }
            }
            
            canvas.width = width;
            canvas.height = height;
            
            // 绘制压缩后的图片
            ctx.drawImage(img, 0, 0, width, height);
            
            // 转换为Blob
            canvas.toBlob((blob) => {
                if (blob) {
                    const compressedFile = new File([blob], file.name, {
                        type: file.type,
                        lastModified: Date.now()
                    });
                    resolve(compressedFile);
                } else {
                    resolve(file);
                }
            }, file.type, quality);
        };
        
        img.src = URL.createObjectURL(file);
    });
};

// 图片预览功能
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');

const previewImage = (url: string) => {
    if (url) {
        previewImageUrl.value = url;
        imagePreviewVisible.value = true;
    }
};

// 图片加载错误处理
const handleImageError = (event: Event) => {
    const img = event.target as HTMLImageElement;
    img.src = ''; // 默认占位图
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = async (rawFile) => {
    const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg';
    const isLt5M = rawFile.size / 1024 / 1024 < 5; // 放宽到5MB，因为我们会压缩

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!');
        return false;
    }
    if (!isLt5M) {
        ElMessage.error('上传图片大小不能超过 5MB!');
        return false;
    }
    
    // 如果图片大于1MB，进行压缩
    if (rawFile.size / 1024 / 1024 > 1) {
        try {
            const compressedFile = await compressImage(rawFile);
            console.log(`图片压缩：${(rawFile.size / 1024 / 1024).toFixed(2)}MB -> ${(compressedFile.size / 1024 / 1024).toFixed(2)}MB`);
            // 替换原文件
            Object.defineProperty(rawFile, 'size', { value: compressedFile.size });
            Object.defineProperty(rawFile, 'stream', { value: () => compressedFile.stream() });
            Object.defineProperty(rawFile, 'arrayBuffer', { value: () => compressedFile.arrayBuffer() });
        } catch (error) {
            console.error('图片压缩失败:', error);
            ElMessage.warning('图片压缩失败，将使用原图上传');
        }
    }
    
    return true;
}


// 提交表单
const AddCarousel = () => {
    if (!carouselFormRef.value) return;
    
    carouselFormRef.value.validate((valid: boolean) => {
        if (valid) {
            // 验证是否已上传图片
            if (!carouselForm.imageUrl) {
                ElMessage.error('请先上传轮播图');
                return;
            }
            
            // 验证时间
            if (!carouselForm.startTime || !carouselForm.endTime) {
                ElMessage.error('请选择开始时间和结束时间');
                return;
            }
            
            // 准备提交数据，确保时间格式正确
            const submitData = {
                ...carouselForm,
                startTime: carouselForm.startTime ? new Date(carouselForm.startTime).toISOString() : null,
                endTime: carouselForm.endTime ? new Date(carouselForm.endTime).toISOString() : null
            };
            
            console.log('提交数据:', submitData);
            
            addPCarouselChart(submitData)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message);
                        dialogVisible.value = false;
                        show();
                    } else {
                        ElMessage.error(res.data.message);
                    }
                })
                .catch(error => {
                    ElMessage.error('新增轮播图失败');
                    console.error(error);
                });
        } else {
            ElMessage.error('请填写完整的表单信息');
        }
    });
}

// 更新轮播图
const updateCarousel = () => {
    if (!carouselFormRef.value) return;
    
    carouselFormRef.value.validate((valid: boolean) => {
        if (valid) {
            // 验证ID
            if (!currentEditId.value) {
                ElMessage.error('编辑ID不能为空');
                return;
            }
            
            // 验证是否已上传图片
            if (!carouselForm.imageUrl) {
                ElMessage.error('请先上传轮播图');
                return;
            }
            
            // 验证时间
            if (!carouselForm.startTime || !carouselForm.endTime) {
                ElMessage.error('请选择开始时间和结束时间');
                return;
            }
            
            // 准备提交数据，确保时间格式正确
            const submitData = JSON.parse(JSON.stringify({
                id: parseInt(currentEditId.value || '0'),
                title: carouselForm.title?.trim() || '',
                imageUrl: carouselForm.imageUrl?.trim() || '',
                status: Boolean(carouselForm.status),
                linkUrl: carouselForm.linkUrl?.trim() || '',
                sortOrder: parseInt(carouselForm.sortOrder) || 0,
                startTime: carouselForm.startTime ? new Date(carouselForm.startTime).toISOString() : null,
                endTime: carouselForm.endTime ? new Date(carouselForm.endTime).toISOString() : null
            }));
            
            console.log('更新数据:', submitData);
            
            UpdatePCarouselChart(submitData)
                .then((res: any) => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message || '更新成功');
                        dialogVisible.value = false;
                        show();
                    } else {
                        ElMessage.error(res.data.message || '更新失败');
                    }
                })
                .catch((error: any) => {
                    ElMessage.error('更新轮播图失败');
                    console.error(error);
                });
        } else {
            ElMessage.error('请填写完整的表单信息');
        }
    });
}

// 删除轮播图
const deleteCarousel = (row: any) => {
    ElMessageBox.confirm(
        `确定要删除轮播图"${row.title}"吗？删除后不可恢复。`,
        '删除确认',
        {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger'
        }
    ).then(() => {
        // 用户确认删除
        const deleteData = {
            id: row.id
        };
        
        console.log('删除轮播图，ID:', row.id);
        
        deleteCarouselChart(deleteData)
            .then((res: any) => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message || '删除成功');
                    // 刷新列表
                    show();
                } else {
                    ElMessage.error(res.data.message || '删除失败');
                }
            })
            .catch((error: any) => {
                ElMessage.error('删除轮播图失败');
                console.error(error);
            });
    }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除');
    });
}

// 批量删除
const batchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的轮播图');
        return;
    }

    const selectedTitles = selectedRows.value.map(row => row.title).join('、');
    
    ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 个轮播图吗？\n\n包括：${selectedTitles}\n\n删除后不可恢复。`,
        '批量删除确认',
        {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger'
        }
    ).then(() => {
        // 用户确认批量删除
        const deletePromises = selectedRows.value.map(row => {
            const deleteData = { id: row.id };
            return deleteCarouselChart(deleteData);
        });

        console.log('批量删除轮播图，IDs:', selectedRows.value.map(row => row.id));

        // 并发执行所有删除请求
        Promise.all(deletePromises)
            .then((responses: any[]) => {
                const successCount = responses.filter(res => res.data.code == 200).length;
                const failCount = responses.length - successCount;

                if (failCount === 0) {
                    ElMessage.success(`成功删除 ${successCount} 个轮播图`);
                } else if (successCount === 0) {
                    ElMessage.error(`删除失败，共 ${failCount} 个轮播图删除失败`);
                } else {
                    ElMessage.warning(`部分删除成功：成功 ${successCount} 个，失败 ${failCount} 个`);
                }

                // 刷新列表
                show();
            })
            .catch((error: any) => {
                ElMessage.error('批量删除轮播图失败');
                console.error(error);
                // 即使出错也刷新列表，因为可能有部分成功
                show();
            });
    }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消批量删除');
    });
}
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 轮播图列表头部样式 */
.carousel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  margin: 20px 0 16px 0;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  margin-right: 8px;
  color: #606266;
  font-size: 16px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 选择信息样式 */
.selection-info {
  margin-left: 16px;
  padding: 4px 12px;
  background-color: #e1f3ff;
  color: #409eff;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* 批量操作按钮组样式 */
.batch-operations {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 12px;
  border-left: 1px solid #e4e7ed;
}

/* 对话框样式 */
.carousel-form {
  padding: 20px 0;
}

.carousel-form .el-form-item {
  margin-bottom: 24px;
}

.carousel-form .el-form-item__label {
  font-weight: 500;
  color: #303133;
}

/* 图片上传样式 */
.upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-placeholder:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.image-preview {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 排序提示样式 */
.sort-tip {
  margin-left: 12px;
  font-size: 12px;
  color: #909399;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 20px;
}

.dialog-footer .el-button {
  min-width: 80px;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

/* 表格图片样式 */
.table-image-container {
  width: 150px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
}

.table-image-container:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  transform: scale(1.02);
}

.table-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.table-image:hover {
  transform: scale(1.05);
}

/* 图片预览对话框样式 */
.image-preview-dialog .el-dialog__body {
  padding: 20px;
  text-align: center;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-image-container {
    width: 100px;
    height: 80px;
  }
  
  .avatar-uploader .avatar,
  .avatar-uploader .el-upload,
  .el-icon.avatar-uploader-icon {
    width: 150px;
    height: 120px;
  }
  
  .image-preview-dialog {
    width: 90% !important;
  }
  
  .preview-image {
    max-height: 50vh;
  }
}

@media (max-width: 480px) {
  .table-image-container {
    width: 80px;
    height: 60px;
  }
  
  .avatar-uploader .avatar,
  .avatar-uploader .el-upload,
  .el-icon.avatar-uploader-icon {
    width: 120px;
    height: 100px;
  }
}
</style>